const localUtils = {
  /**
   * @vuese
   * @Description:
   * @param {*} arr 需去重的数组
   * @param {*} field 根据哪个字段
   */
  delRepetition: ({ arr, field }) => {
    let obj = {};
    arr = arr.reduce(function (item, next) {
      Object.prototype.hasOwnProperty.call(next, field) && obj[next[field]] ? '' : (obj[next[field]] = true && item.push(next));
      return item;
    }, []);
    return arr;
  },
  /**
   * @vuese
   * @Description:从this中获取参数
   * @arg {*} field
   */
  getArgs: (_this, field) => {
    if (field.indexOf('.') !== -1) {
      const args = field.split('.');
      return localUtils.findArgs(_this, args);
    }
    return field;
  },
  /**
   * @vuese
   * @Description: 获取值
   * @arg {*} _this this指向
   * @arg {*} args 参数 如："aa.bb.cc"
   * @arg {*} value 结果
   */
  findArgs: (_this, args, value = {}) => {
    if (args.length == 0) return value;
    let v = (value && value[args[0]]) || _this[args[0]];
    args.splice(0, 1);
    const res = localUtils.findArgs(_this, args, v);
    if (res) return res;
    return null;
  },
  // 找路径
  treeFindPath: ({ tree, func, childrenKey = 'children', valueKey = 'code', path = [] }) => {
    if (!tree) return [];
    for (const data of tree) {
      path.push(data[valueKey]);
      if (func(data)) return path;
      if (data[childrenKey]) {
        const findChildren = localUtils.treeFindPath({
          tree: data[childrenKey],
          func,
          path,
          childrenKey,
          valueKey,
        });
        if (findChildren.length) return findChildren;
      }
      path.pop();
    }
    return [];
  },
  // 找对象
  treeFind: ({ tree, func, childrenKey = 'children' }) => {
    for (const data of tree) {
      if (func(data)) return data;
      if (data[childrenKey]) {
        const res = localUtils.treeFind({ tree: data[childrenKey], func });
        if (res) return res;
      }
    }
    return null;
  },
  /**
   * @Description: 递归设置深层属性
   * @arg {*} src //需要设置的数据对象
   * @arg {*} key //需要设置的路径 如：'aa.bb.cc'
   * @arg {*} value //需要设置的值
   * @function: setObjAttr
   * @return {*} retSrc 返回被修改后的原对象
   */
  setObjAttr(src, key, value) {
    if (Object.prototype.toString.call(src) !== '[object Object]') {
      console.error('[CRUD Error]：被赋值的只能为对象------');
      return;
    }
    if (key.indexOf('.') == -1) {
      console.error('[CRUD Error]：请使用该格式"aa.bb.cc.dd"');
      return;
    }
    const keyArr = key.split('.');
    let retSrc = { ...src };
    if (keyArr instanceof Array && keyArr.length !== 0) {
      for (let index in keyArr) {
        if (index != keyArr.length - 1) {
          let currentVal = {};
          retSrc[keyArr[index]] = currentVal;
          retSrc = currentVal;
        } else {
          retSrc[keyArr[index]] = value;
        }
      }
    }
    return retSrc;
  },
};

export default localUtils;
